package com.woniu.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.dto.EmployeeInfoDto;
import com.woniu.dto.EmployeeNameDTO;
import com.woniu.dto.UserInfoDTO;
import com.woniu.dto.UserWorkerDetailDTO;
import com.woniu.exception.XinanException;
import com.woniu.exception.user.UserException;
import com.woniu.param.SelectUserInfoParam;
import com.woniu.param.UpdateUserInfoParam;
import com.woniu.user.entity.AreaCode;
import com.woniu.user.entity.EmployeeInfo;
import com.woniu.user.entity.UserInfo;
import com.woniu.user.mapper.EmployeeInfoMapper;
import com.woniu.user.service.AreaCodeService;
import com.woniu.user.service.EmployeeInfoService;
import com.woniu.utils.EnumException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 维修员工表 服务实现类
 * </p>
 *
 * @author ly
 * @since 2024年12月05日
 */
@Service
public class EmployeeInfoServiceImpl extends ServiceImpl<EmployeeInfoMapper, EmployeeInfo> implements EmployeeInfoService {
    @Resource
    EmployeeInfoMapper employeeInfoMapper;

    @Resource
    AreaCodeService areaCodeService;

    @Override
    public void updateEmployeeInfo(Integer userId, String profession) {
        EmployeeInfo employeeInfo = employeeInfoMapper.selectByUserId(userId);
        employeeInfo.setProfession(profession);
        this.updateById(employeeInfo);
    }

    @Override
    public List<EmployeeNameDTO> selectEmployeeById() throws Exception {
        List<EmployeeInfo> employeeInfos = employeeInfoMapper.selectList(null);
        if (employeeInfos == null) {
            throw new Exception("用户不存在");
        }
        List<EmployeeNameDTO> employeeNameDTOS = BeanUtil.copyToList(employeeInfos, EmployeeNameDTO.class);
        return employeeNameDTOS;
    }

    @Override
    public PageInfo<EmployeeInfoDto> queryWorkerList(SelectUserInfoParam param) throws Exception {
        try {
            // 设置默认值
            int pageNum = param.getPageNum() == null ? 1 : param.getPageNum();
            int pageSize = param.getPageSize() == null ? 10 : param.getPageSize();

            // 启动分页插件
            PageHelper.startPage(pageNum, pageSize);

            // 执行查询
            List<EmployeeInfo> result = employeeInfoMapper.selectWorkerList(param);

            // 构建 PageInfo 对象
            PageInfo<EmployeeInfo> pageInfo = new PageInfo<>(result);
            List<EmployeeInfoDto> dtoList = BeanUtil.copyToList(pageInfo.getList(), EmployeeInfoDto.class);

            PageInfo<EmployeeInfoDto> userInfoDTOPageInfo = new PageInfo<>(dtoList);
            userInfoDTOPageInfo.setTotal(pageInfo.getTotal());
            userInfoDTOPageInfo.setPageNum(pageInfo.getPageNum());
            userInfoDTOPageInfo.setPageSize(pageInfo.getPageSize());
            userInfoDTOPageInfo.setPages(pageInfo.getPages());
            return userInfoDTOPageInfo;
        } catch (IllegalArgumentException e) {
            throw e;
        } catch (Exception e) {
            throw e;
        }
    }

    @Override
    public Integer updateWorkerInfo(List<UpdateUserInfoParam> params) throws XinanException {
        if (params == null || params.isEmpty()) {
            throw new UserException(EnumException.USER_NULL_EXCEPTION);
        }

        List<EmployeeInfo> userInfosToUpdate = new ArrayList<>();

        for (UpdateUserInfoParam param : params) {
            if (param == null) {
                continue; // 跳过无效参数
            }

            EmployeeInfo employeeInfo = employeeInfoMapper.selectById(param.getEmployeeInfoId());
            if (employeeInfo == null) {
                throw new UserException(EnumException.USER_NULL_EXCEPTION);
            }

            if ("1".equals(employeeInfo.getUserState())) {
                throw new IllegalArgumentException("用户ID " + param.getUserId() + " 已禁用");
            }

            if (param.getAreaCodeName() == null || param.getAreaCodeName().isEmpty()) {
                AreaCode byId = areaCodeService.getById(param.getAreaCodeId());
                if (byId == null) {
                    throw new IllegalArgumentException("区域ID " + param.getAreaCodeId() + " 不存在");
                }
                param.setAreaCodeName(byId.getAreaCodeName());
            }

            employeeInfo.setExpand1(String.valueOf(param.getAreaCodeId()));
            employeeInfo.setExpand2(param.getAreaCodeName());


            userInfosToUpdate.add(employeeInfo);
        }

        if (!userInfosToUpdate.isEmpty()) {
            employeeInfoMapper.batchUpdateUserInfos(userInfosToUpdate);
        }

        return userInfosToUpdate.size();
    }

    /**
     * 更新员工信息状态
     *
     * @param userId 用户ID，用于标识需要更新信息的员工
     * @throws XinanException 如果操作失败，抛出此异常
     */
    @Override
    public void updateEmployeeInfoStatus(String userId) throws XinanException {
        // 检查用户ID是否为空或无效，如果true，则抛出用户空异常
        if (userId == null || userId.isEmpty()) {
            throw new UserException(EnumException.USER_NULL_EXCEPTION);
        }

        // 根据用户ID查询员工信息，准备更新其状态
        EmployeeInfo employeeInfo = employeeInfoMapper.selectByUserId(Integer.parseInt(userId));

        // 检查员工信息是否为空，如果true，则抛出用户空异常
        if (employeeInfo == null) {
            throw new UserException(EnumException.USER_NULL_EXCEPTION);
        }
        employeeInfo.setUserState(3);

        // 执行员工信息的更新操作，条件是用户ID匹配
        employeeInfoMapper.update(employeeInfo, new QueryWrapper<EmployeeInfo>().eq("user_id", userId));
    }

    /**
     * 根据区域代码查询员工信息列表
     *
     * @param areaCodeId 区域代码ID，用于查询特定区域的员工信息
     * @return 返回一个员工信息DTO列表，包含指定区域的所有员工信息
     * @throws Exception 如果查询过程中发生错误或未找到员工信息，则抛出异常
     */
    @Override
    public List<EmployeeInfoDto> queryWorkerListAreaCode(String areaCodeId) throws Exception {
        // 检查区域ID是否为空或无效
        if (areaCodeId == null || areaCodeId.isEmpty()) {
            throw new IllegalArgumentException("区域ID不能为空");
        }
        // 执行查询
        List<EmployeeInfo> result = employeeInfoMapper.queryWorkerListAreaCode(areaCodeId);
        // 检查查询结果是否为空
        if (result == null || result.isEmpty()) {
            throw new UserException(EnumException.USER_NULL_EXCEPTION);
        }
        // 构建返回值
        List<EmployeeInfoDto> dtoList = BeanUtil.copyToList(result, EmployeeInfoDto.class);
        return dtoList;
    }

    @Override
    public void disableWorker(String userId) throws Exception {
        if (userId == null || userId.isEmpty()) {
            throw new UserException(EnumException.USER_NULL_EXCEPTION);
        }
        EmployeeInfo employeeInfo = employeeInfoMapper.selectByUserId(Integer.parseInt(userId));
        if (employeeInfo == null) {
            throw new UserException(EnumException.USER_NULL_EXCEPTION);
        }
        employeeInfo.setUserState(1);
        employeeInfoMapper.updateById(employeeInfo);
    }

    @Override
    public void enableWorker(String userId) throws Exception {
        if (userId == null || userId.isEmpty()) {
            throw new UserException(EnumException.USER_NULL_EXCEPTION);
        }
        EmployeeInfo employeeInfo = employeeInfoMapper.selectByUserId(Integer.parseInt(userId));
        if (employeeInfo == null){
            throw new UserException(EnumException.USER_NULL_EXCEPTION);
        }
        employeeInfo.setUserState(0);
        employeeInfoMapper.updateById(employeeInfo);
    }

    @Override
    public void deleteWorker(String userId) throws Exception {
        if (userId == null || userId.isEmpty()) {
            throw new UserException(EnumException.USER_NULL_EXCEPTION);
        }
        EmployeeInfo employeeInfo = employeeInfoMapper.selectByUserId(Integer.parseInt(userId));
        if (employeeInfo == null) {
            throw new UserException(EnumException.USER_NULL_EXCEPTION);
        }
        employeeInfo.setUserState(2);
        employeeInfoMapper.updateById(employeeInfo);
    }


}
